package a4_queue.impl;

import a4_queue.Queue;

import java.util.NoSuchElementException;

/**
 * 基于链表实现的基础队列
 */
public class MyQueue<E> implements Queue<E> {

    //---------------------
    //链表的每个节点
    private class Node {
        E val;
        Node next;
        Node(E val) {
            this.val = val;
        }
    }
    //---------------------

    private int size;
    private Node head;
    private Node tail;

    @Override
    public void offer(E val) {
        Node node = new Node(val);
        if(head == null){
            head = tail = node;
        }else{
            //尾插
            tail.next = node;
            tail = node;
        }
        size ++;
    }

    @Override
    public E poll() {
        if(isEmpty()){
            throw new NoSuchElementException("queue is empty! cannot poll!");
        }
        Node node = head;
        head = head.next;
        node.next = null;
        size --;
        return node.val;
    }

    @Override
    public E peek() {
        if(isEmpty()){
            throw new NoSuchElementException("queue is empty! cannot peek!");
        }
        return head.val;
    }

    @Override
    public boolean isEmpty() {
        return size == 0;
    }

    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append("front [");
        for(Node x = head; x != null; x = x.next) {
            sb.append(x.val);
            if(x.next != null){
                sb.append(" ,");
            }
        }
        sb.append("]");
        return sb.toString();
    }
}
